package com.jeehentor.generate.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeehentor.common.api.SystemCommonAPI;
import com.jeehentor.common.exception.HentorException;
import com.jeehentor.generate.dto.*;
import com.jeehentor.generate.entity.SysGenModel;
import com.jeehentor.generate.entity.SysGenModelField;
import com.jeehentor.generate.entity.SysGenPage;
import com.jeehentor.generate.mapper.SysGenPageMapper;
import com.jeehentor.generate.service.ISysGenFormService;
import com.jeehentor.generate.service.ISysGenModelService;
import com.jeehentor.generate.service.ISysGenPageService;
import com.jeehentor.generate.utils.CamelCaseUtil;
import com.jeehentor.generate.vo.SysGenPageDetailVO;
import com.jeehentor.utils.SecurityUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Map;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class SysGenPageServiceImpl extends ServiceImpl<SysGenPageMapper, SysGenPage> implements ISysGenPageService {
    private final ISysGenFormService sysGenFormService;
    private final ISysGenModelService sysGenModelService;
    private final SysGenPageMapper sysGenPageMapper;
    private final SystemCommonAPI systemCommonAPI;
    @Override
    public SysGenPageDetailVO selectPageDetail(String id) {
        SysGenPageDetailVO sysGenPageDetailVO = new SysGenPageDetailVO();
        // 查询页面配置
        SysGenPage byId = this.getById(id);
        if(byId == null){
            throw new HentorException("页面配置不存在");
        }
        //查询表单配置
        sysGenPageDetailVO.setGenPage(byId);
        GenFormSaveDTO genFormSaveDTO = new GenFormSaveDTO();
        SysGenFormDTO sysGenFormDTO = new SysGenFormDTO();
        sysGenFormDTO.setId(byId.getFormId());
        genFormSaveDTO.setFormConfig(sysGenFormDTO);
        GenFormSaveDTO genForm = sysGenFormService.selectFormDetail(genFormSaveDTO);
        sysGenPageDetailVO.setGenForm(genForm);
        //查询模型配置
        GenModelDTO genModelDTO = new GenModelDTO();
        genModelDTO.setId(byId.getModelId());
        GenModelDTO genModel = sysGenModelService.selectModelById(genModelDTO);
        sysGenPageDetailVO.setGenModel(genModel);
        //页面组件封装
        String queryField = byId.getQueryField();
        if(StringUtils.isNotBlank(queryField)){
            ArrayList<FormSchema> formSchemas = new ArrayList<>();
            String[] split = queryField.split(",");
            for (String filed : split) {
                FormSchema formSchema = new FormSchema();
                Optional<SysGenModelField> first = genModel.getFieldList().stream().filter(x -> x.getFieldName().equals(filed)).findFirst();
                if(first.isPresent()){
                    //查询组件
                    formSchema.setComponent(first.get().getSearchModule());
                    //字段名
                    formSchema.setField(first.get().getFieldName());
                    //字段备注
                    formSchema.setLabel(first.get().getRemarks());
                }
                formSchemas.add(formSchema);
            }
            sysGenPageDetailVO.setFormSchemas(formSchemas);
        }
        String showField = byId.getShowField();
        if(StringUtils.isNotBlank(showField)){
            ArrayList<TableColumn> tableColumns = new ArrayList<>();
            String[] split = showField.split(",");
            for (String filed : split) {
                TableColumn tableColumn = new TableColumn();
                Optional<SysGenModelField> first = genModel.getFieldList().stream().filter(x -> x.getFieldName().equals(filed)).findFirst();
                if(first.isPresent()){
                    //宽度
                    if(StringUtils.isNotBlank(first.get().getColumnWidth())){
                        tableColumn.setWidth(Integer.parseInt(first.get().getColumnWidth()));
                    }
                    //字段名
                    tableColumn.setField(first.get().getFieldName());
                    //字段备注
                    tableColumn.setLabel(first.get().getRemarks());
                }
                tableColumns.add(tableColumn);
            }
            sysGenPageDetailVO.setTableColumns(tableColumns);
        }
        return sysGenPageDetailVO;
    }

    @Override
    public Page<Map<String,Object>> selectByModel(GenCommonDTO dto) {
        //校验模型信息
        checkModel(dto);
        return sysGenPageMapper.selectTable(dto.getPage(),dto);
    }

    @Override
    public void saveByModel(GenCommonDTO dto) {
        //校验模型信息
        checkModel(dto);
        dto.getFormData().put("id",IdWorker.getIdStr());
        dto.getFormData().put("create_by", SecurityUtil.getCurrentUser().getId());
        sysGenPageMapper.saveByModel(dto);
    }

    @Override
    public void updateByModel(GenCommonDTO dto) {
        //校验模型信息
        checkModel(dto);
        dto.getFormData().put("update_by", SecurityUtil.getCurrentUser().getId());
        sysGenPageMapper.updateByModel(dto);
    }

    @Override
    public void deleteByModel(GenCommonDTO dto) {
        //校验模型信息
        checkModel(dto);
        sysGenPageMapper.deleteByModel(dto);
    }

    private void checkModel(GenCommonDTO dto){
        if(StringUtils.isBlank(dto.getModelId())){
            throw new HentorException("modelId不能为空");
        }
        SysGenModel byId = sysGenModelService.getById(dto.getModelId());
        if(byId == null){
            throw new HentorException("模型不存在");
        }
        dto.setTableName(byId.getTableName());
        if("0".equals(byId.getSyncStatus())){
            //同步数据库
            GenModelDTO genModelDTO = new GenModelDTO();
            genModelDTO.setId(byId.getId());
            try {
                sysGenModelService.syncDataBase(genModelDTO);
            } catch (SQLException e) {
                log.error("同步数据库失败",e);
            }
        }
    }

    @Override
    public void publish(PublishDTO dto){
        SysGenPage sysGenPage = this.getById(dto.getPageId());
        if(sysGenPage == null){
            throw new HentorException("页面配置不存在");
        }
        SysGenModel sysGenModel = sysGenModelService.getById(sysGenPage.getModelId());
        if(sysGenModel == null){
            throw new HentorException("模型配置不存在");
        }
        //查询菜单是否存在
        JSONObject menu = systemCommonAPI.existMenu(dto.getParentMenuId(), CamelCaseUtil.underscoreToCamelCase(sysGenModel.getTableName(), true));
        if(ObjectUtil.isNotNull(menu)){
            menu.put("title",dto.getTitle());
            systemCommonAPI.updateMenu(menu);
            sysGenPage.setMenuTitle(dto.getTitle());
            this.updateById(sysGenPage);
            systemCommonAPI.addRoleMenu(dto.getRoles(),String.valueOf(menu.get("id")));
        }else {
            JSONObject menuDTO = new JSONObject();
            menuDTO.put("type","1");
            menuDTO.put("parentId",dto.getParentMenuId());
            menuDTO.put("title",dto.getTitle());
            menuDTO.put("component","views/lowCode/page/PageConfig");
            menuDTO.put("name",CamelCaseUtil.underscoreToCamelCase(sysGenModel.getTableName(),true));
            menuDTO.put("path",CamelCaseUtil.underscoreToCamelCase(sysGenModel.getTableName(),false));
            menuDTO.put("status","1");
            JSONObject sysMenuMeta = new JSONObject();
            sysMenuMeta.put("noCache","1");
            menuDTO.put("meta",sysMenuMeta);
            JSONObject jsonObject = systemCommonAPI.addMenu(menuDTO);
            sysGenPage.setMenuId(String.valueOf(jsonObject.get("id")));
            sysGenPage.setMenuTitle(dto.getTitle());
            sysGenPage.setMenuName(CamelCaseUtil.underscoreToCamelCase(sysGenModel.getTableName(),true));
            this.updateById(sysGenPage);
            systemCommonAPI.addRoleMenu(dto.getRoles(),String.valueOf(jsonObject.get("id")));
        }
    }

}
